<template>
  <!--基础信息-->
  <div style="width: 100%;" v-show="show">
    <el-collapse v-model="activeName">
      <el-collapse-item title="基本信息" name="1">
        <el-form :disabled="dialogType() === 'view'"
                 ref="form"
                 size="medium"
                 :rules="rules[temp]"
                 :model="formData"
                 label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="中文名称：" prop="nameCn">
                <el-input v-model="formData.nameCn"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="编码标识：" prop="name">
                <el-input v-model="formData.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="英文名称：" prop="nameEn">
                <el-input v-model="formData.nameEn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="父模型：" prop="parentName">
                <el-select style="width: 100%" v-model="formData.parentName" @change="parentIdChange">
                  <template v-for="item in parentIdList()">
                    <el-option :label="item.nameCn" :value="item.name"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="componentName" label="模型类型：" prop="type">
                <el-select style="width: 100%" v-model="formData.type">
                  <template v-for="item in modelTypeList()">
                    <el-option :key="item.oid" :value="item.value" :label="item.name"></el-option>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item v-else label="模型类型：" prop="refType">
                <el-select style="width: 100%" v-model="formData.refType">
                  <template v-for="item in typeList">
                    <el-option :key="item.oid" :value="item.value" :label="item.name"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24" v-if="componentName">
              <el-form-item label="表名称：" prop="tableName">
                <el-input v-model="formData.tableName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="componentName">
            <el-col :span="24">
              <el-form-item label="是否抽象：" prop="abstractFlag">
                <el-radio-group v-model="formData.abstractFlag">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="英文描述：">
                <el-input v-model="formData.describeEn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="中文描述：" prop="describeCn">
                <el-input v-model="formData.describeCn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


          <el-row>
            <el-col :span="12" v-if="componentName">
              <el-form-item label="标签：">
                <el-input></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="componentName">
              <el-form-item label="图标：">
                <avue-input-icon v-model="formData.icon"
                                 :icon-list="iconList"
                                 :modal-append-to-body="false"
                                 placeholder="图标"></avue-input-icon>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12" v-if="!componentName">
              <el-form-item label="是否联动修改：" prop="isGanged">
                <el-radio-group v-model="formData.isGanged">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="!componentName">
              <el-form-item label="是否树形：" prop="isTree">
                <el-radio-group v-model="formData.isTree">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-show="!componentName">
            <el-col :span="12">
              <el-form-item label="From实体：" prop="fromOid">
                <el-select multiple style="width: 100%" v-model="formData.fromOid">
                  <template v-for="{code,name} in entityModulesList">
                    <el-option :label="name" :value="code"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="To实体：" prop="toOid">
                <el-select multiple style="width: 100%" v-model="formData.toOid">
                  <template v-for="{code,name} in entityModulesList">
                    <el-option :label="name" :value="code"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12" v-if="!componentName">
              <el-form-item label="表名：" prop="tableName">
                <el-input v-model="formData.tableName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="功能列表" name="2">
        <avue-crud :option="baseInfoOption"
                   v-if="show&&showThisTabs"
                   :table-loading="loading"
                   @selection-change="v=>selection=v"
                   :data="formData.functionInterfaces"
                   ref="crud">
          <template slot="extendsFlag" slot-scope="{row}">
            <i style="font-size: 16px" :class="row.extendsFlag===1?'el-icon-check':'el-icon-close'"></i>
          </template>

          <template slot="menuLeft">
            <el-button :disabled="dialogType() === 'view'" size="medium" type="primary"
                       @click="$refs['gdcd'].open(formData.functionInterfaces)">添加
            </el-button>
            <el-button :disabled="dialogType() === 'view'" size="medium" @click="remove">移除</el-button>
          </template>
        </avue-crud>
      </el-collapse-item>
    </el-collapse>
    <get-data-common-dialog title="选择功能"
                            ref="gdcd"
                            :param="{type:2}"
                            url="/api/manager-api/mx-interface/page"
                            :column="EntityInterfaceOption.column"
                            @addToList="addToList">
    </get-data-common-dialog>
  </div>
</template>

<script>
import iconList from "@/config/iconList";

import * as interfaceApi from "@/api/modulManage/interface";
import * as entity from "@/api/modulManage/entity"
import GetDataCommonDialog from "@/views/DMDComponent/getDataCommonDialog.vue";
import {getDic} from "@/api/common";

export default {
  name: "baseInfo",
  components: {GetDataCommonDialog},
  inject: ["temp", "parentIdList", "modelTypeList", "EntityInterfaceOption", "allFormData", "baseInfoOption", "dialogType"],
  props: {
    show: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    showThisTabs: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
  },
  data() {
    return {
      activeName: ["1", "2"],
      form: {
        "EM": {
          nameCn: "",
          name: "",
          parentName: "",
          nameEn: "",
          type: "",
          describeEn: "",
          describeCn: "",
          icon: "",
          functionInterfaces: [],
          tableName: ""
        },
        "ER": {
          nameCn: "",
          name: "",
          parentName: "",
          nameEn: "",
          refType: "",
          describeEn: "",
          describeCn: "",
          isTree: "",
          isGanged: "",
          toOid: "",
          fromOid: "",
          functionInterfaces: [],
          tableName: ""
        }
      },
      rules: {
        "EM": {
          tableName: [{required: true, message: "请输入表名称", trigger: "blur"}],
          nameCn: [{required: true, message: "请输入中文名称", trigger: "blur"}],
          name: [{required: true, message: "请输入编码标识", trigger: "blur"}],
          parentName: [{required: true, message: "请选择父模型", trigger: "change"}],
          nameEn: [{required: true, message: "请输入英文名称", trigger: "blur"}],
          type: [{required: true, message: "请选择模型类型", trigger: "change"}],
          abstractFlag: [{required: true, message: "请选择是否抽象", trigger: "change"}],
          describeCn: [{required: true, message: "请输入中文描述", trigger: "blur"}],
        },
        "ER": {
          tableName: [{required: true, message: "请输入表名称", trigger: "blur"}],
          nameCn: [{required: true, message: "请输入中文名称", trigger: "blur"}],
          name: [{required: true, message: "请输入编码标识", trigger: "blur"}],
          parentName: [{required: true, message: "请选择父模型", trigger: "change"}],
          nameEn: [{required: true, message: "请输入英文名称", trigger: "blur"}],
          refType: [{required: true, message: "请选择模型类型", trigger: "change"}],
          describeCn: [{required: true, message: "请输入中文描述", trigger: "blur"}],
          isTree: [{required: true, message: "请选择是否树形", trigger: "change"}],
          isGanged: [{required: true, message: "请选择是否联动修改", trigger: "change"}],
          fromOid: [{required: true, message: "请选择from实体", trigger: "change"}],
          toOid: [{required: true, message: "请选择to实体", trigger: "change"}],
        },
      },
      iconList: iconList,

      data: [],
      loading: false,

      selection: [],

      entityModulesList: [],

      typeList: []
    }
  },
  computed: {
    formData() {
      return this.form[this.temp];
    },
    componentName() {
      return this.temp === "EM";
    }
  },
  methods: {
    /*
    * 删除功能列表数据
    * */
    remove() {
      // let data = this.deepCopy(this.selection).map(item => item.oid);
      let data = this.deepCopy(this.selection).map(item => item.extendsFlag === 0 ? item.oid : "");
      let properties = this.deepCopy(this.formData.functionInterfaces);
      this.formData.functionInterfaces = [];
      properties.forEach(item => {
        if (data && !data.includes(item.oid)) {
          this.formData.functionInterfaces.push(item);
        }
      })
    },
    /**
     * @param list 添加到功能列表
     * */
    addToList(list) {
      let properties = this.deepCopy(this.formData.functionInterfaces);
      this.formData.functionInterfaces = [];
      if (properties.length > 0) {

        let ids = properties.map(item => item.oid ? item.oid : -1);
        list.forEach(item => {
          if (ids.length > 0 && item.oid && !ids.includes(item.oid)) {
            properties.push(item);
          }
        })
      } else {
        properties.push(...list);
      }

      this.$nextTick(() => {
        this.formData.functionInterfaces = properties;
        this.$refs['gdcd'].close();
      })
    },
    /**
     *@param v 父模型 变化 关联功能列表
     * */
    parentIdChange(v) {
      if (!v) return;
      let item = {};
      let treePath = "";
      this.parentIdList().forEach(i => {
        if (i.name === v) {
          item = i;
        }
      })
      if (item.treePath) {
        treePath = item.treePath + ","
      }
      treePath += item.oid;
      let functionInterfaces = this.deepCopy(this.formData.functionInterfaces);

      interfaceApi.getFather({typeIds: treePath}).then(res => {
        this.formData.functionInterfaces = [];
        if (res.data.data.length !== 0) {
          res.data.data.forEach(item => {
            this.formData.functionInterfaces.push({...item, ...{"extendsFlag": 1}})
          })
          // this.formData.functionInterfaces = res.data.data;
        }
        /* if (res.data.data.length !== 0) {
           // 如果 功能列表已经有值 那么就需要移除与继承父类重复的值
           if (functionInterfaces.length !== 0) {
             let ids = res.data.data.map(item => item.oid);
             this.formData.functionInterfaces = [];
             functionInterfaces.forEach(item => {
               if (ids && !ids.includes(item.oid)) {
                 this.formData.functionInterfaces.push({...item, ...{"extendsFlag": 0}});
               }
             })
           }

           let oids = this.formData.functionInterfaces.map(i => i.oid);

           // 将从父类继承的值 写入
           res.data.data.forEach(item => {
             if (oids.includes(item.oid)) {
               this.$set(this.formData.functionInterfaces[oids.indexOf(item.oid)], "extendsFlag", 1);
             } else {
               item.extendsFlag = 1;
               this.formData.functionInterfaces.unshift(item);
             }
           })
         } else {
           this.formData.functionInterfaces = [];
           // 如果继承父类的值为空，则移除上一次所继承父类的值
           this.formData.functionInterfaces = functionInterfaces.filter(item => item.extendsFlag !== 1);
         }*/

        this.$refs["crud"].refreshTable();
      })
    },

    async getTabData() {
      return {form: this.deepCopy(this.formData), flag: await this.$refs['form'].validate()};
    },

    setTabData() {

    },

    /**
     * @param type 类型 view/edit
     * @param data 数据
     * */
    view_edit(type, data) {
      if (!this.showComponent) {
        data.fromOid = this.deepCopy(data.fromList);
        data.toOid = this.deepCopy(data.toList);
      }

      for (const key in data) {
        this.$set(this.formData, key, data[key]);
      }
    },
    /**
     * 获取from/to实体
     * */
    getEntityModulesList() {
      entity.getEntityLatest().then(res => {
        this.entityModulesList = res.data.data;
      })
    },
    /*
    * 关系实体 获取关系类型
    * */
    getType() {
      getDic("refenrenceEnum").then(res => {
        this.typeList = res.data.data;
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs["form"].clearValidate();
    })
  },
  created() {
    if (!this.componentName) {
      this.getEntityModulesList()
      this.getType()
    }
  },
  watch: {
   /* "formData.parentId": {
      handler(v) {
        this.parentIdChange(v);
      },
      immediate: true,
      deep: true
    },*/
    show: {
      handler(v) {
        if (v) {
          const {step1, saveFirst} = this.allFormData();
          let form = saveFirst ? step1 : this.allFormData();
          Object.assign(this.formData, form);

          this.$nextTick(() => {
            this.$refs["crud"].refreshTable();
          })
        }
      }
    }
  }
}
</script>
